/**
* @desc:  人员管理-添加组织
* @author qiankui
* @date 2023-4-15 15:38:06
*/
<template>
    <el-dialog :close-on-click-modal="false" :visible="addOrgFlag" class="zdy-dialog" width="650px" :title="$t('Add organization')"
               :lock-scroll="false" :before-close="handleCloseDialog">
        <div class="el-dialog-div">
            <el-form :model="form" class="pop-form-box" :rules="rules" ref="ruleForm">
              <!--组织选择-->
              <el-form-item :label="$t('organizational choice')" prop="zzid">
                <el-cascader
                    style="width: 100%;"
                    v-model="form.zzid"
                    :props="defaultProps"
                    :options="orgInfo"
                    :show-all-levels="false"
                >
                  <template slot-scope="{ node, data }">
                    <span>{{ data.name }}</span>
                    <span v-if="data.departmentInfos!==undefined"> ({{ data.departmentInfos.length }}) </span>
                  </template>
                </el-cascader>
              </el-form-item>
              <!--组织名称-->
              <el-form-item :label="$t('organization name')" prop="zzName" :rules="$rules.req">
                <el-input v-model="form.zzName" ref="zzName" :minlength="$rules.orgName.min" :maxlength="$rules.orgName.max"
                          show-word-limit></el-input>
              </el-form-item>
            </el-form>
        </div>
        <div class="footBtnBox">
            <el-button size="small" type="handle" @click="handleCloseDialog">{{this.i18n.t('Cancel')}}</el-button>
            <el-button size="small" type="primary" :loading="saveLoading" @click="save">{{this.i18n.t('save')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import {getParentsById,filterLastTreeData} from '../utils.js'
    import {departmentinfoCreate,personnelinfoCreate,getdepartmenttree} from "@/api/pcmj/zzxx";
    export default {
        name: "addDevice",
        props: {
            addOrgFlag: {
                type: Boolean,
                default: false
            },
            handleType: {
                type: String,
                default: 'add'
            },
            leftTreeAddData: {
                type: Object,
                default: function () {
                  return {
                      name:{}
                  }
                }
            },
        },
        data() {
            var validateZZName = (rule, value, callback) => {
                value=value||""
                if (value == '') {
                    // 请输入组织名称
                    callback(new Error(this.i18n.t('Please enter an organization name')));
                }else if (!this.$rules.orgName.reg.test(value)) {
                    callback(new Error(this.$rules.orgName.min+'~'+this.$rules.orgName.max+' ' + this.i18n.t('bits')));
                }else {
                    callback();
                }
            };
            var validateZZId = (rule, value, callback) => {
                if (value == ''||value==undefined) {
                    // 请选择组织
                    callback(new Error(this.i18n.t('Please select an organization')));
                }else {
                    callback();
                }
            };
            return {
                rules: {
                    zzid:[
                        {validator: validateZZId,required: true, trigger: 'blur'}
                    ],
                    zzName:[
                        {validator: validateZZName,required: true, trigger: 'blur'}
                    ]
                },
                defaultProps: {
                    children: 'departmentInfos',
                    label: 'name',
                    value:'id',
                    checkStrictly: true
                },
                activeName: '0',
                sex: 0,
                saveLoading: false,
                orgInfo: [],
                form: {
                    zzid:"",
                    name:'',
                    personnelCode:'',
                    sex:0,
                    telephone:'',
                    imagePath:'',
                    departmentInfoId: '',
                    zzName: ''
                }
            }
        },
        mounted(){
            this.$nextTick(async () => {
                console.log(this.$refs.zzName.focus());;
            })

            // debugger
            if(!Object.keys(this.leftTreeAddData).length){
                this.form.zzid=-1
            }
            console.log('leftTreeAddData',this.leftTreeAddData);
            // this.form=this.leftTreeAddData
            this.getdepartmenttree()
        },
        methods: {
            /**
             * @description  获取部门人员树
             * @param :
             **/
            getdepartmenttree() {
                this.$nextTick(async () => {
                    getdepartmenttree({IncludePersonInfo: false}).then((res) => {
                        if (res.code === 200) {
                            // 把最后一级children是空的设置成null
                            this.orgInfo=filterLastTreeData(res.data.rootDepartments)
                            // 无组织
                            var tempObj={
                                id: -1,
                                name: this.i18n.t('no organization'),
                                parentId:-1
                            }
                            this.orgInfo.push(tempObj)
                            this.form.zzid=getParentsById(this.orgInfo, this.leftTreeAddData.id||this.form.zzid)
                        }
                    }).catch().finally(() => {

                    })

                });
            },
            // 刷新人员页面左侧组织树、右侧表格数据
            parentUpdate(){
                this.$emit("update:addOrgFlag",false);
                this.$parent.getdepartmenttree()
            },
            // 添加人员
            personnelinfoCreate(params){
                personnelinfoCreate(params).then((res) => {
                    if (res.code === 200) {
                        // 添加成功
                        this.W.$tips("success", this.i18n.t('Add successfully!'))
                      this.parentUpdate()
                    }
                }).catch().finally(() => {
                    setTimeout(() => {
                        // this.leftTreeLoading = false
                    }, 500)
                })
            },
            // 添加组织
            departmentinfoCreate(params){
              this.saveLoading=true
                departmentinfoCreate(params).then((res) => {
                    if (res.code === 200) {
                        // 添加成功
                        this.W.$tips("success", this.i18n.t('Add successfully!'))
                        this.parentUpdate()
                    }
                }).catch().finally(() => {
                    setTimeout(() => {
                      this.saveLoading=false
                        // this.leftTreeLoading = false
                    }, 500)
                })
            },
            save(){
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        var params={}
                        // 创建组织
                        params={
                            name:this.form.zzName,
                            parentId:this.leftTreeAddData.id
                        }
                        if(!Object.keys(this.leftTreeAddData).length){
                            params.parentId=this.form.zzid[this.form.zzid.length-1]
                            if(params.parentId==-1){
                                params.parentId=null
                            }
                        }
                        console.log(239,params);
                        this.departmentinfoCreate(params)
                    }else {
                        console.log('error submit!!',this.$refs.ruleForm.validate);
                        return false;
                    }
                })
            },
            handleCloseDialog() {
                this.$emit('update:addOrgFlag', false);
            }
        }
    }
</script>

<style scoped>
    .el-dialog-div{
        height:250px;
        overflow-x: hidden;
    }

</style>
